package com.jy.importclient.common.util;

import com.jy.importclient.common.constants.ExpConstants;
import com.jy.importclient.common.dto.VerifyFile;
import com.jy.importclient.common.enums.ExpEnum;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名 FileUtil
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/4/24 17:21
 * @版本 1.0
 */
public class FileUtil {

    public static String getFile(String fileName, String msg) throws Exception {
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File(fileName)))) {
            byte[] buffer = new byte[1024];
            int len = 0;
            StringBuilder builder = new StringBuilder();
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                builder.append(new String(buffer, 0, len));
            }
            return builder.toString();
        } catch (IOException e) {
            //文件不存在反馈
            throw new Exception(msg);
        }
    }
    
    public static Map<String, Object> check(String datFileContext, String filePath, VerifyFile verifyFile) throws IOException {
        Map<String, Object> map = new HashMap<>();
        //计算每个接口文件的记录行数和文件大小
        long records = StringUtil.countRecords(datFileContext);
        long fileSize = StringUtil.getFileSize(filePath);
        //校验记录行数
        if (!Long.valueOf(verifyFile.getFileRecords()).equals(records)) {
            map.put("flag", false);
            map.put("msg", ExpConstants.RECORDS_EXP + "，检测数据文件总行数是：" + records);
            map.put("code", ExpEnum.RECORDS_EXP.getCode());
            return map;
        }
        //校验文件大小
        if (!Long.valueOf(verifyFile.getFileBytesSize()).equals(fileSize)) {
            map.put("flag", false);
            map.put("msg", ExpConstants.FILE_SIZE_EXP + "，检测数据文件总大小：" + fileSize);
            map.put("code", ExpEnum.FILE_SIZE_EXP.getCode());
            return map;
        }
        map.put("flag", true);
        return map;
    }

    public static String createDirectories(String path) throws IOException {
        boolean exists = new File(path).exists();
        Path path1 = Paths.get(path);
        if (!exists) {
            return Files.createDirectories(path1).toString();
        }
        return path1.toString();
    }

    public static void createFile(String context, String path) {
        File file = new File(path);
        try (BufferedOutputStream ous = new BufferedOutputStream(new FileOutputStream(file))) {
            ous.write(context.getBytes(StandardCharsets.UTF_8));
            ous.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String createCtlFile(VerifyFile verifyFile, String ctlContext, String filePath) throws IOException {
        String fileName = StringUtil.createFileName(verifyFile.getDatFileName());
        String directories = FileUtil.createDirectories(filePath + "/file_ctl");
        String path = StringUtil.concat(new StringBuffer(), directories, "/", fileName);
        FileUtil.createFile(ctlContext,  path);
        return fileName;
    }

    //递归删除目录下指定文件
    public static boolean removeFile(String path, String fileName) {
        File[] files = new File(path).listFiles();
        if (files != null) {
            for(File f : files) {
                if (f.isFile() && f.getName().equals(fileName)) {
                    return f.delete();
                }
                removeFile(f.getPath(), fileName);
            }
        }
        return false;
    }

    public static byte[] getBytes(String filePath) {
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getFileName(String filePath) {
        int i = filePath.indexOf("=");
        return filePath.substring(i + 1);
    }

    public static String getSuffix(String filePath) {
        int index = filePath.lastIndexOf(".");
        return filePath.substring(index + 1);
    }

    public static List<VerifyFile> getFailFileList(List<VerifyFile> verifyFileList, List<String> fileNames) {
        List<VerifyFile> verifyFiles = new ArrayList<>();
        for (VerifyFile verifyFile : verifyFileList) {
            for (String fileName : fileNames) {
                if (verifyFile.getDatFileName().equals(fileName)) {
                    verifyFiles.add(verifyFile);
                }
            }
        }
        return verifyFiles;
    }

    public static boolean isEmptyFile(String datFileContext, String filePath) throws IOException {
        return StringUtil.countRecords(datFileContext) == 0 || StringUtil.getFileSize(filePath) == 0;
    }
}
